import base64
import random
import time
import struct
import hashlib

# 插件版
# appId="com.chunmi.mijia.microwave"
appId = "202007190935010"
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1])]



def encryptBase64(src):
    return base64.b64encode(src).strip().replace("\n", "").replace("\r", "")

def sha256(src):
    return hashlib.sha256(src.encode("utf-8")).digest()

def generateNonce():
    """
    生成nonce
    """
    src = bytearray()

    for i in range(8):
        src.append(random.randint(0, 255))
    #print('src',src)
    mill = int(round(time.time() * 1000))
    #print ('aa', mill)
    t = struct.pack(">i", mill//60000)
    #print('bb', t)
    src.extend(t)
    #print(src.extend(t))
    resultt= str(base64.b64encode(src))
    result2=resultt.split("'")[1]
    #print(result2)
    return result2
def generateTimestamp():
    ticks = round(time.time() * 1000)
    # print "当前时间戳为:", ticks
    return int(ticks)

def generateSignature(nonce,timestamp, http_method, http_url):
    """
    生成signature
    """
    s1=appId + "&" + str(timestamp)+ "&" +nonce+ "&"+ http_method + "&" + http_url
    resultt = str(base64.urlsafe_b64encode(sha256(s1)))
    result2 = resultt.split("'")[1]
    result3=result2.strip().replace("\n", "").replace("\r", "").replace('/', "")
    return result3
